package com.cn.jinl.service;


import com.cn.jinl.api.IDeviceService;
import com.cn.jinl.api.ILinePeiService;
import com.cn.jinl.api.IOnDutyPersonService;
import com.cn.jinl.api.ISterilizeService;
import com.cn.jinl.dao.*;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.NumberUtil;
import com.cn.jinl.utils.QueryForm;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@EnableScheduling
@Service
public class LinePeiServiceImpl implements ILinePeiService {

    @Autowired
    private LinePeiMapper linePeiMapper;

    @Autowired
    private LinePeiAttrMapper linePeiAttrMapper;

    @Autowired
    private LinePeiBanMapper linePeiBanMapper;

    @Autowired
    private LinePeiOutMapper linePeiOutMapper;

    @Autowired
    private ProcureStorageOutHisMapper procureStorageOutHisMapper;

    @Autowired
    private IOnDutyPersonService onDutyPersonService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private ISterilizeService sterilizeService;

    @Autowired
    private LineBanMqttMapper lineBanMqttMapper;

    @Autowired
    private ProcureStorageMapper procureStorageMapper;


    @Override
    public Map<String,Object> getLinePeiListMap(QueryForm queryForm) throws Exception {
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");

        String banZhang = onDutyPersonService.getOnDutyPersonByDutyAndWhite(dutyDay,whiteDay);
        LinePeiExample example = new LinePeiExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay);
        example.setOrderByClause("device_code asc");
        List<LinePei> linePeis = linePeiMapper.selectByExample(example);
        Map<String,LinePei> linePeiMap = Maps.newLinkedHashMap();
        List<String> peiIds = Lists.newArrayList();
        for(LinePei linePei :linePeis){
            linePeiMap.put(linePei.getDeviceCode(),linePei);
            peiIds.add(linePei.getId());
        }
        Map<String,Double>OutMap = Maps.newHashMap();
        Map<String,LinePeiBan>banMap = Maps.newHashMap();
        if(CollectionUtils.isNotEmpty(peiIds)){
            LinePeiBanExample banExample = new LinePeiBanExample();
            banExample.createCriteria().andPeiIdIn(peiIds);
            banExample.setOrderByClause("create_time desc");
            List<LinePeiBan> bans = linePeiBanMapper.selectByExample(banExample);
            for(LinePeiBan ban:bans){
                if(banMap.containsKey(ban.getPeiId())){
                    continue;
                }
                banMap.put(ban.getPeiId(),ban);
            }

            LinePeiOutExample outExample = new LinePeiOutExample();
            outExample.createCriteria().andPeiIdIn(peiIds);
            List<LinePeiOut> existsPieOut = linePeiOutMapper.selectByExample(outExample);
            for(LinePeiOut outs:existsPieOut){
                if(OutMap.containsKey(outs.getPeiId())){
                    double v = OutMap.get(outs.getPeiId());
                    if(StringUtils.isNotEmpty(outs.getClValue())){
                        v += Double.parseDouble(outs.getClValue());
                        OutMap.put(outs.getPeiId(),v);
                    }
                }else{
                    if(StringUtils.isNotEmpty(outs.getClValue())){
                        double v = Double.parseDouble(outs.getClValue());
                        OutMap.put(outs.getPeiId(),v);
                    }
                }
            }
        }

        Map<String,List<String>> deviceMaps = deviceService.getDeviceByProcName("配拌投料","");
        List<LinePei> results = Lists.newLinkedList();
        for(String key :deviceMaps.keySet() ){
            List<String> deviceCodes = deviceMaps.get(key);
            for(String code : deviceCodes){
                if(linePeiMap.containsKey(code)){
                    LinePei mapLine = linePeiMap.get(code);
                    if(banMap.containsKey(mapLine.getId())){
                        LinePeiBan _ban = banMap.get(mapLine.getId());
                        String banTimePeriod = (StringUtils.isEmpty(_ban.getStartTime())?"":_ban.getStartTime().split(" ")[1])+"-"+(StringUtils.isEmpty(_ban.getEndTime())?"":_ban.getEndTime().split(" ")[1]);
                        mapLine.setBanTimePeriod(banTimePeriod);
                        String convertMin = "0";
                        if(StringUtils.isNotEmpty(_ban.getCollectTime())){
                            double min = Double.parseDouble(_ban.getCollectTime())/60.0;
                            convertMin = NumberUtil.getPoint(min,1);
                        }
                        mapLine.setBanTimeCount(convertMin);
                    }
                    String unOutValue = mapLine.getTotalValue();
                    if(OutMap.containsKey(mapLine.getId())){
                        double hasOut = OutMap.get(mapLine.getId());
                        double dist = Double.parseDouble(unOutValue) - hasOut;
                        unOutValue = NumberUtil.getPoint(dist,2);
                    }
                    mapLine.setUnOutValue(unOutValue);
                    results.add(mapLine);
                }else{
                    LinePei add = new LinePei();
                    add.setDeviceCode(code);
                    if(StringUtils.equals(code,"B01")){
                        add.setGpName("U直");
                    }else if(StringUtils.equals(code,"B02")){
                        add.setGpName("伸直");
                    }else if(StringUtils.equals(code,"B03")){
                        add.setGpName("普直");
                    }
                    add.setPlStatus("0");
                    results.add(add);
                }
            }

        }
        Collections.sort(results, new Comparator<LinePei>() {
            @Override
            public int compare(LinePei o1, LinePei o2) {
                if(o1.getDeviceCode().compareTo(o2.getDeviceCode()) < 0){
                    return -1;
                }
                return 1;
            }
        });
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("linePeis",results);
        resultMap.put("dutyDay",dutyDay);
        resultMap.put("whiteDay",whiteDay);
        resultMap.put("banzhang",banZhang);
        return resultMap;
    }

    @Override
    public String addLinePei(LinePei linePei) throws Exception {
        List<LinePeiAttr> linePeiAttrs = linePei.getLinePeiAttrs();

        if(CollectionUtils.isEmpty(linePeiAttrs)){
            return "参数异常！";
        }
        List<LinePeiBan> linePeiBans = linePei.getLinePeiBans();
        if(CollectionUtils.isEmpty(linePeiBans)){
            return "参数异常！";
        }
        linePei.setPlStatus("1");
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");

        linePei.setWhiteDay(whiteDay);
        linePei.setDutyDay(dutyDay);
        LinePeiExample example = new LinePeiExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andDeviceCodeEqualTo(linePei.getDeviceCode());
        List<LinePei> linePeis = linePeiMapper.selectByExample(example);
        String oldId  = linePei.getOldId();
        if(CollectionUtils.isNotEmpty(linePeis) && StringUtils.isEmpty(oldId)){
            return "记录已经存在!";
        }
        String id = CommonUtil.generateRandomNum("linepei-");
        linePei.setId(id);
        double zlValue = 0.0;
        double flValue = 0.0;
        double smValue = 0.0;
        double totalValue = 0.0;
        for(LinePeiAttr linePeiAttr:linePeiAttrs){
            linePeiAttr.setPeiId(id);
            if(StringUtils.equals(linePeiAttr.getMaterialType(),"主料")){
                zlValue+=Double.parseDouble(linePeiAttr.getJtValue());
            }else if(StringUtils.equals(linePeiAttr.getMaterialType(),"辅料")){
                flValue+=Double.parseDouble(linePeiAttr.getJtValue());
            }else if(StringUtils.equals(linePeiAttr.getMaterialType(),"色母")){
                smValue+=Double.parseDouble(linePeiAttr.getJtValue());
            }
        }
        totalValue = zlValue+flValue+smValue;
        linePei.setZlValue(NumberUtil.getPoint(zlValue,2));
        linePei.setFlValue(NumberUtil.getPoint(flValue,2));
        linePei.setSmValue(NumberUtil.getPoint(smValue,2));
        linePei.setTotalValue(NumberUtil.getPoint(totalValue,2));
        LinePeiBan  linePeiBan= linePeiBans.get(0);
        linePeiBan.setPeiId(id);
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = simpleDateFormat.format(new Date());
//        linePeiBan.setStartTime(time);

        int count = linePeiMapper.insertSelective(linePei);
        if(count < 1){
            return "插入失败！";
        }

        count = linePeiAttrMapper.batchInsertLinePeiAttrs(linePeiAttrs);
        if(count < 1){
            throw new Exception("插入失败！");
        }

        count = linePeiBanMapper.insertSelective(linePeiBan);
        if(count < 1){
            throw new Exception("插入失败2");
        }
        Sterilize sterilize = new Sterilize();
        sterilize.setDeviceCode(linePei.getDeviceCode());
//        sterilize.setDutyDay(dutyDay);
//        sterilize.setWhiteDay(whiteDay);
        sterilize.setSterilizeType("1");
        sterilize.setTabName("配拌投料");
        sterilize.setSterilizeWater("75%酒精");
        sterilize.setSterilizeUserName(linePei.getPlUserName());
        String resp = sterilizeService.addSterilize(sterilize);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        if(StringUtils.isNotEmpty(oldId)){
            count = linePeiMapper.updateLinePeiStatusByOldId(oldId);
            if(count < 1){
                throw new Exception("更新旧记录异常！");
            }
        }
        return resp;
    }

    @Override
    public String updateLinePei(LinePei linePei) throws Exception {
        String id = linePei.getId();
        if(StringUtils.isEmpty(id)){
            return this.addLinePei(linePei);
        }

        LinePei exist = linePeiMapper.selectByKey(id);
        if(null == exist){
            return "数据不存在！";
        }
        if(!StringUtils.equals(exist.getPlStatus(),"0")&&!StringUtils.equals(exist.getPlStatus(),"2")){
            return "状态处于非录入拌料状态！";
        }
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");

        if(!StringUtils.equals(exist.getWhiteDay(),whiteDay)||!StringUtils.equals(exist.getDutyDay(),dutyDay)){
            return "班次已经过期！";
        }

        List<LinePeiBan> linePeiBans = linePei.getLinePeiBans();
        if(CollectionUtils.isEmpty(linePeiBans)){
            return "参数异常！";
        }
        LinePeiBan  linePeiBan= linePeiBans.get(0);
        linePeiBan.setPeiId(id);
        int count = linePeiBanMapper.insertSelective(linePeiBan);
        if(count < 1){
            return "插入拌料异常！";
        }
        LinePei update = new LinePei();
        update.setPlStatus("1");
        LinePeiExample example = new LinePeiExample();
        example.createCriteria().andIdEqualTo(id);
        count = linePeiMapper.updateByExampleSelective(update,example);
        if(count < 1){
            throw new Exception("插入拌料异常!！");
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String addLinePeiOut(LinePeiOut linePeiOut) throws Exception {
        String id = linePeiOut.getPeiId();
        if(StringUtils.isEmpty(id)){
            return "参数异常！";
        }
        LinePei linePei = linePeiMapper.selectByKey(id);
        if(null == linePei){
            return "配料不存在";
        }
        if(!StringUtils.equals(linePei.getPlStatus(),"3")){
            return "不在待出料状态";
        }

        LinePeiOutExample example = new LinePeiOutExample();
        example.createCriteria().andPeiIdEqualTo(id);
        List<LinePeiOut> exists = linePeiOutMapper.selectByExample(example);
        String totalValue = linePei.getTotalValue();
        double outTotalValue = 0.0;
        if(CollectionUtils.isNotEmpty(exists)){
            for(LinePeiOut out :exists){
                outTotalValue += Double.parseDouble(out.getClValue());
            }
        }
        if(Double.parseDouble(totalValue) <= outTotalValue){
            return "未出料为0";
        }
        double outv = outTotalValue + Double.parseDouble(linePeiOut.getClValue());

        if(outv > Double.parseDouble(totalValue)){
            return "出料数量大出总料重！";
        }
        int count = linePeiOutMapper.insertSelective(linePeiOut);
        if(count < 0){
            return "插入出料表异常！";
        }
        if(outv == Double.parseDouble(totalValue)){
            LinePeiExample example1 =  new LinePeiExample();
            example1.createCriteria().andIdEqualTo(id);
            LinePei update = new LinePei();
            update.setPlStatus("4");
            count = linePeiMapper.updateByExampleSelective(update,example1);
            if(count < 0){
                throw new Exception("更新入出料表异常");
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public List<LinePeiAttr> getLinePeiAttrs(String peiId) throws Exception {
        if(StringUtils.isEmpty(peiId)){
            List<LinePeiAttr> linePeiAttrs = Lists.newLinkedList();
            LinePeiAttr attr1 = new LinePeiAttr();
            attr1.setOrderIndex(1);
            attr1.setMaterialType("主料");
            linePeiAttrs.add(attr1);
            LinePeiAttr attr2 = new LinePeiAttr();
            attr2.setOrderIndex(2);
            attr2.setMaterialType("主料");
            linePeiAttrs.add(attr2);

            LinePeiAttr attr3 = new LinePeiAttr();
            attr3.setOrderIndex(3);
            attr3.setMaterialType("辅料");
            linePeiAttrs.add(attr3);

            LinePeiAttr attr4 = new LinePeiAttr();
            attr4.setOrderIndex(4);
            attr4.setMaterialType("辅料");
            linePeiAttrs.add(attr4);

            LinePeiAttr attr5 = new LinePeiAttr();
            attr5.setOrderIndex(5);
            attr5.setMaterialType("色母");
            linePeiAttrs.add(attr5);
            return linePeiAttrs;
        }
        LinePeiAttrExample  example = new LinePeiAttrExample();
        example.createCriteria().andPeiIdEqualTo(peiId);
        example.setOrderByClause("order_index asc");
        return linePeiAttrMapper.selectByExample(example);
    }

    @Override
    public List<LinePeiBan> getLinePeiBans(String peiId) throws Exception {
        if(StringUtils.isEmpty(peiId)){
            return Lists.newArrayList();
        }
        LinePeiBanExample example = new LinePeiBanExample();
        example.createCriteria().andPeiIdEqualTo(peiId);
        example.setOrderByClause("create_time asc");
        List<LinePeiBan> bans = linePeiBanMapper.selectByExample(example);
        for(LinePeiBan ban:bans){
            String collectTime = ban.getCollectTime();
            if(StringUtils.isNotEmpty(collectTime)){
                double dt = Double.parseDouble(collectTime);
                dt = dt/60.0;
                collectTime = NumberUtil.getPoint(dt,2);
                ban.setCollectTime(collectTime);
            }
        }
        return bans;
    }

    @Override
    public List<LinePeiOut> getLinePeiOuts(String peiId) throws Exception {
        if(StringUtils.isEmpty(peiId)){
            return Lists.newArrayList();
        }
        LinePeiOutExample example = new LinePeiOutExample();
        example.createCriteria().andPeiIdEqualTo(peiId);
        return linePeiOutMapper.selectByExample(example);
    }

    @Override
    public List<LinePei> getLinePeiLists(QueryForm queryForm) throws Exception {
        int count = linePeiMapper.selectLineBanListsCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<LinePei> linePeis = linePeiMapper.selectLineBanLists(queryForm);
        for(LinePei pei:linePeis){
            String collectTime = pei.getCollectTime();
            if(StringUtils.isNotEmpty(collectTime)){
                double dt = Double.parseDouble(collectTime);
                dt = dt/60.0;
                collectTime = NumberUtil.getPoint(dt,2);
                pei.setCollectTime(collectTime);
            }
        }
        linePeis.get(0).setCount(count);
        return linePeis;
    }

    @Override
    public Map<String, List<Double>> getFirstPageLinePeis(QueryForm queryForm) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String todayYear = year+"-01-01 00:00:00";
        String endYear = year+"-12-31 23:59:59";
        queryForm.setStartTime(todayYear);
        queryForm.setEndTime(endYear);

        List<LinePeiAttr> peiAttrs = linePeiAttrMapper.selectFirstPageLinePeis(queryForm);

        Map<String,List<Double>> resultMap = Maps.newHashMap();
        resultMap.put("day",Lists.newArrayList(0.0,0.0,0.0));
        resultMap.put("moth",Lists.newArrayList(0.0,0.0,0.0));
        resultMap.put("year",Lists.newArrayList(0.0,0.0,0.0));

        String todayTime = simpleDateFormat.format(new Date());
        String moth = todayTime.split("-")[1];
        for(LinePeiAttr attr:peiAttrs){
            String materialType = attr.getMaterialType();
            String dutyDay = attr.getDutyDay();
            int index = 0;
            if(StringUtils.equals(materialType,"主料")){
                index = 0;
            }else if(StringUtils.equals(materialType,"辅料")){
                index = 1;
            }else {
                index = 2;
            }
            String dutyMoth = dutyDay.split("-")[1];
            String jtValue = attr.getJtValue();
            if(StringUtils.isEmpty(jtValue)){
                continue;
            }
            double value = Double.parseDouble(jtValue);
            if(StringUtils.equals(dutyDay,todayTime)){
                double count = resultMap.get("day").get(index)+value;
                count = Double.parseDouble(NumberUtil.getPoint(count,2));
                resultMap.get("day").set(index,count);
            }else if(StringUtils.equals(moth,dutyMoth)){
                double count = resultMap.get("moth").get(index)+value;
                count = Double.parseDouble(NumberUtil.getPoint(count,2));
                resultMap.get("moth").set(index,count);
            }
            double count = resultMap.get("year").get(index)+value;
            count = Double.parseDouble(NumberUtil.getPoint(count,2));
            resultMap.get("year").set(index,count);
        }
        return resultMap;
    }

    @Override
    public List<LinePei> getFirstLinePeiList() throws Exception {
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
        LinePeiExample example = new LinePeiExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andPlStatusGreaterThan("0");
        example.setOrderByClause("device_code asc");
        List<LinePei> linePeis = linePeiMapper.selectByExample(example);
        List<String> peiIds = Lists.newArrayList();
        for(LinePei linePei :linePeis){
            peiIds.add(linePei.getId());
        }
        Map<String,LinePeiBan>banMap = Maps.newHashMap();
        if(CollectionUtils.isNotEmpty(peiIds)){
            LinePeiBanExample banExample = new LinePeiBanExample();
            banExample.createCriteria().andPeiIdIn(peiIds);
            banExample.setOrderByClause("create_time desc");
            List<LinePeiBan> bans = linePeiBanMapper.selectByExample(banExample);
            for(LinePeiBan ban:bans){
                if(banMap.containsKey(ban.getPeiId())){
                    continue;
                }
                banMap.put(ban.getPeiId(),ban);
            }
        }
        for(LinePei linePei:linePeis){
            if(banMap.containsKey(linePei.getId())){
                LinePeiBan _ban = banMap.get(linePei.getId());
                String banTimePeriod = (StringUtils.isEmpty(_ban.getStartTime())?"":_ban.getStartTime().split(" ")[1])+"-"+(StringUtils.isEmpty(_ban.getEndTime())?"":_ban.getEndTime().split(" ")[1]);
                linePei.setBanTimePeriod(banTimePeriod);
                linePei.setBanTimeCount(_ban.getCollectTime());
            }
        }
        return linePeis;
    }

    @Override
    public Map<String, Object> getFirstPageFuLiaoInfo() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = simpleDateFormat.format(new Date());
        String queryTime = startTime.split("-")[0]+"-01-01";
        List<LinePeiAttr> linePeiAttrs =  linePeiAttrMapper.selectPeiBanAttrs(queryTime);
        double zlTodayCount = 0.0;
        double zlMothCount = 0.0;
        double zlYearCount = 0.0;

        double flTodayCount = 0.0;
        double flMothCount = 0.0;
        double flYearCount = 0.0;

        double smTodayCount = 0.0;
        double smMothCount = 0.0;
        double smYearCount = 0.0;
        String currentMoth = startTime.split("-")[1];
        for(LinePeiAttr attr:linePeiAttrs){
            String materialType = attr.getMaterialType();
            String banTime = simpleDateFormat.format(attr.getCreateTime());
            if(StringUtils.equals(materialType,"主料")){
                if(StringUtils.equals(banTime,startTime)){
                    zlTodayCount += Double.parseDouble(attr.getJtValue());
                }
                if(StringUtils.equals(currentMoth,banTime.split("-")[1])){
                    zlMothCount += Double.parseDouble(attr.getJtValue());
                }
                zlYearCount += Double.parseDouble(attr.getJtValue());
            }else if(StringUtils.equals(materialType,"辅料")){
                if(StringUtils.equals(banTime,startTime)){
                    flTodayCount += Double.parseDouble(attr.getJtValue());
                }
                if(StringUtils.equals(currentMoth,banTime.split("-")[1])){
                    flMothCount += Double.parseDouble(attr.getJtValue());
                }
                flYearCount += Double.parseDouble(attr.getJtValue());
            }else if(StringUtils.equals(materialType,"色母")){
                if(StringUtils.equals(banTime,startTime)){
                    smTodayCount += Double.parseDouble(attr.getJtValue());
                }
                if(StringUtils.equals(currentMoth,banTime.split("-")[1])){
                    smMothCount += Double.parseDouble(attr.getJtValue());
                }
                smYearCount += Double.parseDouble(attr.getJtValue());
            }
        }
        Map<String,Object> attrsMap = Maps.newHashMap();
        attrsMap.put("zlTodayCount",NumberUtil.getPoint(zlTodayCount,2));
        attrsMap.put("zlMothCount",NumberUtil.getPoint(zlMothCount,2));
        attrsMap.put("zlYearCount",NumberUtil.getPoint(zlYearCount,2));
        attrsMap.put("flTodayCount",NumberUtil.getPoint(flTodayCount,2));
        attrsMap.put("flMothCount",NumberUtil.getPoint(flMothCount,2));
        attrsMap.put("flYearCount",NumberUtil.getPoint(flYearCount,2));
        attrsMap.put("smTodayCount",NumberUtil.getPoint(smTodayCount,2));
        attrsMap.put("smMothCount",NumberUtil.getPoint(smMothCount,2));
        attrsMap.put("smYearCount",NumberUtil.getPoint(smYearCount,2));

        List<ProcureStorageOutHis> procureStorageOutHisList = procureStorageOutHisMapper.selectProcureOutStorage();
        Map<String,Double> outMaps = Maps.newHashMap();
        for(ProcureStorageOutHis outHis:procureStorageOutHisList){
            outMaps.put(outHis.getMaterialId(),Double.parseDouble(outHis.getOutCount()));
        }
//        List<LinePeiAttr> linePeiAttrs1 = linePeiAttrMapper.selectPeiBanAttrLeftStorage();
        List<ProcureStorage> procureStorages = procureStorageMapper.selectProcureLeftStorage();
        attrsMap.put("zlStorage",0.0);
        attrsMap.put("flStorage",0.0);
        attrsMap.put("smStorage",0.0);
        for(ProcureStorage procureStorage:procureStorages){
            String materialId = procureStorage.getMaterialId();
            double val = Double.parseDouble(procureStorage.getProcureExistCount());
            if(outMaps.containsKey(materialId)){
                val = val - outMaps.get(materialId);
            }
            if(StringUtils.equals("主料",materialId)){
                attrsMap.put("zlStorage",val);
            }else if(StringUtils.equals("辅料",materialId)){
                attrsMap.put("flStorage",val);
            }else if(StringUtils.equals("色母",materialId)){
                attrsMap.put("smStorage",val);
            }
        }

//        for(LinePeiAttr attr:linePeiAttrs1){
//            String materialType = attr.getMaterialType();
//            String key = "";
//            if(StringUtils.equals("主料",materialType)){
//                key = "zlStorage";
//            }else if(StringUtils.equals("辅料",materialType)){
//                key = "flStorage";
//            }else if(StringUtils.equals("色母",materialType)){
//                key = "smStorage";
//            }
//            if(StringUtils.isNotEmpty(key)){
//                double count = Double.parseDouble(attr.getJtValue());
//                double left = (Double)attrsMap.get(key) - count ;
//                if(left < 0){
//                    left = 0;
//                }
//                attrsMap.put(key,left);
//            }
//        }
        attrsMap.put("zlStorage",NumberUtil.getPoint((Double)attrsMap.get("zlStorage"),2));
        attrsMap.put("flStorage",NumberUtil.getPoint((Double)attrsMap.get("flStorage"),2));
        attrsMap.put("smStorage",NumberUtil.getPoint((Double)attrsMap.get("smStorage"),2));
        return attrsMap;
    }

    @Scheduled(cron = "*/55 * * * * ?")
    public void updateLinePeiBan() throws Exception {
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");

        String time = dutyDay+" 00:00:00";
        List<LineBanMqtt> lineBanMqtts = lineBanMqttMapper.selectLineBanMqtts(time);
//        if(CollectionUtils.isEmpty(lineBanMqtts)){
//            return;
//        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,LineBanMqtt> lineBanMqttMap = Maps.newHashMap();
        for(LineBanMqtt lineBanMqtt : lineBanMqtts){
            String banAlias = lineBanMqtt.getBanAlias();
            if(lineBanMqttMap.containsKey(banAlias)){
                continue;
            }
            lineBanMqttMap.put(banAlias,lineBanMqtt);
        }

        LinePeiExample example = new LinePeiExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andPlStatusEqualTo("1");
        List<LinePei> linePeis = linePeiMapper.selectByExample(example);
        List<String> lineIds = Lists.newArrayList();
        if(CollectionUtils.isEmpty(linePeis)){
            return;
        }
        for(LinePei linePei : linePeis){
            lineIds.add(linePei.getId());
        }
        LinePeiBanExample banExample = new LinePeiBanExample();
        banExample.createCriteria().andPeiIdIn(lineIds);
        banExample.setOrderByClause("create_time desc");
        List<LinePeiBan> linePeiBans = linePeiBanMapper.selectByExample(banExample);
        Iterator<LinePeiBan> iterator = linePeiBans.iterator();
        List<String> repeatIds = Lists.newArrayList();
        Map<String,String> lineBanRepMap = Maps.newHashMap();
        while (iterator.hasNext()){
            LinePeiBan next = iterator.next();
            if(repeatIds.contains(next.getPeiId())){
                if(StringUtils.isNotEmpty(next.getStartTime())&& !lineBanRepMap.containsKey(next.getBanName())){
                    lineBanRepMap.put(next.getBanName(),next.getStartTime());
                }
                iterator.remove();
                continue;
            }
            repeatIds.add(next.getPeiId());
        }
        List<LinePeiBan> updates = Lists.newArrayList();
        List<LinePei> linePeiList = Lists.newArrayList();
        long  nowTimeStamp = new Date().getTime();
        for(LinePeiBan linePeiBan:linePeiBans){
            String banName = linePeiBan.getBanName();
            if(lineBanMqttMap.containsKey(banName)){
                LineBanMqtt mqtt = lineBanMqttMap.get(banName);
                if(lineBanRepMap.containsKey(banName)&&lineBanRepMap.get(banName).equals(mqtt.getStartTime())){
                }else{
                    double targetTime = Double.parseDouble(linePeiBan.getTimeTarget());
                    //如果相差目标分钟，认为这条开机数据不对
                    if((linePeiBan.getCreateTime().getTime() - simpleDateFormat.parse(mqtt.getStartTime()).getTime()) >= targetTime*60L*1000L){
                    }else{
                        linePeiBan.setStartTime(mqtt.getStartTime());
                        linePeiBan.setEndTime(mqtt.getEndTime());
                        linePeiBan.setCollectTime(mqtt.getMixTime());
                        updates.add(linePeiBan);
                        if(StringUtils.isNotEmpty(mqtt.getEndTime()) ){
                            String plStatus = "3";
                            if((Double.parseDouble(mqtt.getMixTime())-Double.parseDouble(linePeiBan.getTimeTarget())*60.0)< 0){
                                plStatus = "2";
                            }
                            LinePei pei = new LinePei();
                            pei.setId(linePeiBan.getPeiId());
                            pei.setPlStatus(plStatus);
                            linePeiList.add(pei);
                            continue;
                        }
                    }

                }
            }
            String startTime = linePeiBan.getStartTime();
            long createTimeStamp = linePeiBan.getCreateTime().getTime();
            double targetTime = Double.parseDouble(linePeiBan.getTimeTarget());
            LinePei pei = new LinePei();
            if(StringUtils.isNotEmpty(startTime)){
                long startTimeStamp  = simpleDateFormat.parse(startTime).getTime();
                long dist = nowTimeStamp - startTimeStamp;
                //20分钟浮动，超过拌料异常
                if(dist > (targetTime+20)*60L*1000L){
                    if(StringUtils.isNotEmpty(linePeiBan.getCollectTime())){
                        long collectionTime = Long.parseLong(linePeiBan.getCollectTime())*1000L;
                        String endTime = simpleDateFormat.format(new Date(startTimeStamp+collectionTime));
                        linePeiBan.setEndTime(endTime);
                        updates.add(linePeiBan);
                        if(Long.parseLong(linePeiBan.getCollectTime())>=Double.parseDouble(linePeiBan.getTimeTarget())*60.0){
                            pei.setPlStatus("3");
                        }
                    }
                    if(StringUtils.isEmpty(pei.getPlStatus())){
                        pei.setPlStatus("2");
                    }
                }
            }else{
                if((nowTimeStamp - createTimeStamp) > targetTime*60L*1000L){
                    pei.setPlStatus("2");
                }
            }
            if(StringUtils.isNotEmpty(pei.getPlStatus())){
                pei.setId(linePeiBan.getPeiId());
                linePeiList.add(pei);
            }
        }
        if(CollectionUtils.isNotEmpty(updates)){
            int count = linePeiBanMapper.batchUpdateLinePeiBan(updates);
            if(count < 0){
                return;
            }
        }
        if(CollectionUtils.isNotEmpty(linePeiList)){
            int count = linePeiMapper.batchUpdateLinePei(linePeiList);
            if(count < 0){
                throw new Exception("更新拌料表异常1");
            }
        }

    }


}
